import { createSlice, PayloadAction } from "@reduxjs/toolkit";

export interface UserState {
  token: string | null;
  userInfo: {
    id: string;
    name: string;
    avatar?: string;
  } | null;
  isLoading: boolean;
}

const initialState: UserState = {
  token: null,
  userInfo: null,
  isLoading: false,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setToken: (state, action: PayloadAction<string | null>) => {
      state.token = action.payload;
    },
    setUserInfo: (state, action: PayloadAction<UserState["userInfo"]>) => {
      state.userInfo = action.payload;
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.isLoading = action.payload;
    },
    logout: (state) => {
      state.token = null;
      state.userInfo = null;
    },
  },
});

export const { setToken, setUserInfo, setLoading, logout } = userSlice.actions;
export default userSlice.reducer;
